<!--生产制造->需求计划->计划方案-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!--按钮-->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col>
                            <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('productionWorkPlan:add')">
                                <div class="btns" @click="newPlan">
                                    <a-icon class="btns-icon" type="file-add" />
                                    <div class="btns-text">新增</div>
                                </div>
                            </a-col>
                            <a-col :class="planId!=1?'':'btns-disable'" :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('productionWorkPlan:save')">
                                <div class="btns" @click="planId!=1?savePlan():''">
                                    <a-icon class="btns-icon" type="save" />
                                    <div class="btns-text">保存</div>
                                </div>
                            </a-col>
                            <!-- <a-col :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                                <div class="btns">
                                    <a-icon class="btns-icon" type="edit" />
                                    <div class="btns-text">修改</div>
                                </div>
                            </a-col> -->
                            <a-col :class="planId&&planId!=1?'':'btns-disable'" :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl" v-if="permissions.includes('productionWorkPlan:delete')">
                                <div class="btns" @click="planId&&planId!=1?deletePlan():''">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </div>
                            </a-col>
                            <!-- <a-col class="btns-disable" :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                                <div class="btns">
                                    <a-icon class="btns-icon" type="audit" />
                                    <div class="btns-text">审核</div>
                                </div>
                            </a-col>
                            <a-col class="btns-disable" :xs="btnGrid.xs" :sm="btnGrid.sm" :md="btnGrid.md" :lg="btnGrid.lg" :xl="btnGrid.xl">
                                <div class="btns">
                                    <a-icon class="btns-icon" type="audit" />
                                    <div class="btns-text">弃审</div>
                                </div>
                            </a-col> -->
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <!--内容-->
            <section class="work-plan-content">
                <div class="content-left">
                    <h5 style="margin-top:5px;padding-left:5px;">MRP运算方案</h5>
                    <ul class="menu-list">
                        <li v-for="(item,index) in planList" :class="planId == item.id?'active':''" :key="index" @click="planClick(item)">({{item.code}}){{item.name}}</li>
                    </ul>
                </div>
                <div class="content-right">
                    <a-form-model :layout="formLayout">
                        <a-row class="order-dynamic-form-wrapper">
                            <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="方案编码" :rules="[{ required: true, message:'',trigger:'input'}]">
                                    <a-input v-model="code" @keyup="()=>{code=code.replace(/[^\d.]/g,'')}" :value="value"></a-input>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                        <a-row class="order-dynamic-form-wrapper">
                            <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="方案名称" :rules="[{ required: true, message:'',trigger:'input'}]">
                                    <a-input v-model="name"></a-input>
                                </a-form-model-item>
                            </a-col>
                            <a-col :xs="grid.xs" :sm="grid.sm" :md="grid.md" :lg="grid.lg" :xl="grid.xl" :xxl="grid.xxl">
                                <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="方案描述">
                                    <a-input v-model="requestData.remarks"></a-input>
                                </a-form-model-item>
                            </a-col>
                        </a-row>
                    </a-form-model>
                    <a-col :span="24" style="width:600px;">
                        <a-divider orientation="left">
                            运算公式
                        </a-divider>
                    </a-col>
                    <a-col :span="24" class="padding-left-20">
                        <p>净需求量 = 毛需求/(1-损耗率(%)) - (现有库存 - 安全库存 + 预计入库数量 - 已分配数量)</p>

                        <p>计划订单量 = 批量调整(净需求数量/成品率)</p>

                        <a-checkbox-group :options="plainOptions" @change="onChange" v-model="checkBoxField" style="width:600px;">

                        </a-checkbox-group>
                    </a-col>

                    <a-col :span="24" style="width:600px;">
                        <a-divider orientation="left">
                            参与运算的仓库
                        </a-divider>
                    </a-col>
                    <a-col :span="24" class="padding-left-20">
                        <div style="width:350px;">
                            <a-table :columns="columns" :data-source="data" :pagination="false" bordered style="min-height:200px;">
                                <template slot="isMRP" slot-scope="text,record,index">
                                    <a-checkbox :checked="text" @change="hanldCheckbox(record,index,$event)"></a-checkbox>
                                </template>
                            </a-table>
                        </div>
                    </a-col>
                    <a-col :span="24" style="width:600px;">
                        <a-divider orientation="left">
                            运算结果合并规则
                        </a-divider>
                    </a-col>
                    <a-col :span="24" class="padding-left-20">
                        <a-radio-group :options="plainOptionsRadio" v-model="requestData.mergeType" />
                    </a-col>
                </div>
            </section>
        </div>
    </div>
</template>
<script>
import { getAction, postAction } from "@/api/manage";
import { save, list, remove } from "@/api/production/productionMRP";
import { mapState } from "vuex";
export default {

    data() {
        return {
            //----------↓样式----------
            btnGrid: {
                xs: 2,
                sm: 2,
                md: 2,
                lg: 2,
                xl: 2
            },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 6
            },
            formLayout: "inline",
            fromStyle: { paddingTop: "8px" },
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
            editFalse: {
                borderBottom: '1px solid #ded7d7'
            },
            //----------↑样式----------
            plainOptions: [
                { label: '考虑耗损率', value: 'lossRate' },
                { label: '考虑现有库存', value: 'isExistInventory' },
                { label: '考虑成品率', value: 'isFinishProductRate' },
                { label: '考虑安全库存', value: 'isSafeInventory' },
                { label: '考虑预计入库数量和已分配数量', value: 'isWarehouseDistributionQuantity' },
                { label: '净需求考虑订货策略和批量调整', value: 'isOrderPolicyBatch' },
            ],
            plainOptionsRadio: [
                { label: '不合并', value: 1 },
                { label: '物料', value: 2 },
                { label: '物料+来源号', value: 3 },
                { label: '物料+来源号+行号', value: 4 },
            ],
            columns: [{
                title: '序号',
                dataIndex: '',
                width: 50,
                customRender: (text, record, index) => {
                    return <span>{index + 1}</span>
                },
                align: 'center'
            }, {
                title: '仓库编码',
                dataIndex: 'whCode',
            }, {
                title: '仓库名称',
                dataIndex: 'whName',
            }, {
                title: '参与MRP运算',
                dataIndex: 'isMRP',
                scopedSlots: { customRender: 'isMRP' },
                align: 'center'
            }],
            data: [],
            requestData: {
                mergeType: 1,
                warehouseIds: []
            },//提交参数
            warehouseIds: new Map(),//参与运行的仓库,
            checkBoxField: [],//勾选的运算公式
            planList: [],//方案
            planId: null,//当前选中的id
            planName: null,//当前选中的name
            code: null,
            name: null,
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
    },
    created() {
        this.getWhereHouse();
    },
    methods: {
        getWhereHouse() {
            //获取仓库
            let apiUrl = '/in/warehouse/pageList';

            let postData = {
                current: 1,
                size: 20,
                // keyWord: this.inputValue,
            }
            getAction(apiUrl, postData).then(response => {
                if (response.code === 200) {
                    const { records, total, current, size } = response.data;
                    this.data = records;

                    this.getList();

                    // if (this.data.length > 0) {

                    // } else {
                    //     this.$message.warning('您还没有添加仓库！');
                    //     return;
                    // }
                }
            }).catch(error => { });
        },
        hanldCheckbox(record, index, even) {
            if (even.target.checked) {
                // this.warehouseIds.set(record.whCode, record.id);
                this.data.forEach(item => {
                    if (item.id == record.id) {
                        this.$set(item, 'isMRP', true);
                    }
                });
            } else {
                this.data.forEach(item => {
                    if (item.id == record.id) {
                        this.$set(item, 'isMRP', false);
                    }
                });
            }

            this.requestData.warehouseIds = [];
            this.data.forEach(item => {
                if (item.isMRP) {
                    this.requestData.warehouseIds.push(item.id)
                }
            });
            this.requestData.warehouseIds = this.requestData.warehouseIds.join(',');
        },
        onChange(checkedValues) {
            console.log('checked = ', checkedValues);
            this.plainOptions.forEach(item => {
                this.$set(this.requestData, item.value, 0);
                checkedValues.forEach(option => {
                    if (item.value == option) {
                        this.$set(this.requestData, item.value, 1);
                    }
                });
            });
        },
        savePlan() {
            //保存方案
            let requestData = this.requestData;
            if (this.name == '') {
                this.$message.warning('方案名称必须输入');
                return;
            }
            if (this.code == '') {
                this.$message.warning('方案编码必须输入');
                return;
            }
            let reg = /^[0-9]{3}$/;
            if (!reg.test(this.code)) {
                this.$message.warning('方案编码只能输入三位数');
                return;
            }
            requestData.code = this.code;
            requestData.name = this.name;
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.getList();
                } else {
                    this.$message.error(response.message);
                }
            }).catch(e => {

            })

        },
        getList() {
            //获取方案
            let data = {
                current: 1,
                size: -1,
            }
            list(data).then(res => {
                if (res.code === 200) {
                    const { records } = res.data;
                    this.planList = records;
                    if (records.length > 0) {
                        if (this.planId) {
                            let nowData = records.filter(item => item.id == this.planId);
                            this.planClick(nowData[0]);
                        } else {
                            this.planClick(records[0])
                        }
                    }
                }
            })
        },
        planClick(record) {
            console.log(record);
            this.code = record.code;
            this.name = record.name;
            //点击方案
            this.planId = record.id;
            this.planName = record.name;
            this.requestData = record;

            this.checkBoxField = [];
            for (const key in record) {
                if (record[key] === true) {
                    this.checkBoxField.push(key)
                }
            }

            let warehouse = record.warehouseIds.split(',');

            this.data.forEach(key => { this.$set(key, 'isMRP', false) });
            warehouse.forEach(d => {
                this.data.forEach(item => {
                    if (item.id == d) {
                        this.$set(item, 'isMRP', true);
                    }
                });
            })

            //系统默认方案仓库全部勾选
            if (record.isSystem == 1) {
                this.data.forEach(item => {
                    this.$set(item, 'isMRP', true);
                });
            }
        },
        newPlan() {
            //新增方案
            this.code = null;
            this.name = null;
            this.planId = null;
            this.planName = null;
            this.requestData = {
                mergeType: 1
            };
            this.checkBoxField = ['lossRate', 'isExistInventory', 'isFinishProductRate', 'isSafeInventory', 'isWarehouseDistributionQuantity', 'isOrderPolicyBatch'];
            this.onChange(this.checkBoxField)
            this.data.forEach(key => { this.$set(key, 'isMRP', false) });
        },
        deletePlan() {
            let _this = this;
            this.$confirm({
                title: '确认',
                content: `您确定要删除 ${_this.planName} 吗? 删除后数据不能恢复!`,
                onOk() {
                    remove({ id: _this.planId }).then(res => {
                        if (res.code === 200) {
                            _this.$message.success('删除成功', 1);
                            _this.getList();
                            _this.newPlan();
                        }
                    })
                },
                onCancel() { },
            });
        }
    }
}
</script>
<style lang="less">
@import "~@/style/purchase/voucher.less";
.work-plan-content {
    display: flex;
    height: calc(100% - 45px);
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
    .content-left {
        overflow-y: auto;
        flex: 0 0 260px;
        border-right: 4px solid #ddd;
        .menu-list {
            list-style: none;
            margin: 0;
            padding: 0;
            li {
                padding-left: 10px;
                height: 32px;
                line-height: 32px;
                border-bottom: 1px solid #ccc;
                cursor: pointer;
            }
            li:hover {
                background-color: rgba(55, 136, 255, 0.2);
                color: #666;
            }
            li.active {
                background-color: #3788ff;
                color: #fff;
            }
            li:last-child {
                border-bottom: none;
            }
        }
    }
    .content-right {
        flex: 1;
        padding: 10px 60px;
        overflow-y: auto;
        h5 {
            margin: 10px 0;
        }
        .ant-form-inline .ant-form-item {
            display: block;
        }
        .order-dynamic-form-wrapper {
            label:not(.form-check-label):not(.custom-file-label) {
                font-weight: normal;
            }
            .ant-form-item-label,
            .ant-form-item-control {
                line-height: 32px;
            }
        }
        .ant-checkbox-group-item {
            margin-right: 20px;
            height: 32px;
            line-height: 32px;
        }
    }
}
</style>